/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.anniversary.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.modules.anniversary.domain.Student;
import me.zhengjie.modules.anniversary.domain.Teacher;
import me.zhengjie.modules.anniversary.service.DepartmentService;
import me.zhengjie.modules.anniversary.service.StudentService;
import me.zhengjie.modules.anniversary.service.dto.DepartmentDto;
import me.zhengjie.modules.anniversary.service.dto.StudentDto;
import me.zhengjie.modules.anniversary.service.dto.StudentQueryCriteria;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.mapstruct.UserMapper;
import me.zhengjie.utils.FileUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @website https://el-admin.vip
* @author Jiayin Wei
* @date 2020-07-27
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "学生校友管理")
@RequestMapping("/api/student")
public class StudentController {
    private final PasswordEncoder passwordEncoder;
    private final StudentService studentService;
    private final UserService userService;
    private final DepartmentService departmentService;

    private final UserMapper userMapper;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('student:list')")
    public void download(HttpServletResponse response, StudentQueryCriteria criteria) throws IOException {
        studentService.download(studentService.queryAll(criteria), response);
    }

    @Log("批量导入学生校友")
    @ApiOperation("批量导入学生校友")
    @PostMapping(value = "/batchImport")
    @PreAuthorize("@el.check('student:add')")
    public  ResponseEntity<Object> batchImport(MultipartFile file,HttpServletResponse response) throws IOException {
        return new ResponseEntity<>(studentService.batchImport(file,response), HttpStatus.OK);
    }

    @GetMapping
    @Log("查询学生校友")
    @ApiOperation("查询学生校友")
    @PreAuthorize("@el.check('student:list')")
    public ResponseEntity<Object> query(StudentQueryCriteria criteria, Pageable pageable){
        if(criteria.getCollege() != null && !criteria.getCollege().trim().isEmpty()) {
            // 先获得学院信息
            List<DepartmentDto> departments = departmentService.getCollegesByName(criteria.getCollege().trim());

            if(departments!= null && !departments.isEmpty()){
                for (DepartmentDto item : departments) {
                    criteria.getCollegeIds().add(item.getId());
                }
            }
            criteria.setCollege(null);
        }
        // 再in所有学院
        return new ResponseEntity<>(studentService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @GetMapping(value = "/count")
    @Log("查询学生校友人数")
    @ApiOperation("查询学生校友人数")
    @PreAuthorize("@el.check('student:list')")
    public ResponseEntity<Object> count(String college){
        return new ResponseEntity<>(studentService.count(college),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增学生校友")
    @ApiOperation("新增学生校友")
    @PreAuthorize("@el.check('student:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Student resources){
        return new ResponseEntity<>(studentService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改学生校友")
    @ApiOperation("修改学生校友")
    @PreAuthorize("@el.check('student:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Student resources){
        Boolean isVerifyChange = false;
        //若原认证状态不是 0 且认证状态有更改，则需要更新认证时间
        StudentDto student = studentService.findById(resources.getId());
        if(student != null && student.getVerifyStatus() != 0 && student.getVerifyStatus() != resources.getVerifyStatus()){
            isVerifyChange = true;
            resources.setVerifyTime(new Timestamp(System.currentTimeMillis()));
        }

        // 更新学生信息
        studentService.update(resources);

        //同步用户与学生信息表的认证状态
        if(resources.getStudentUser() != null){
            User user =  userMapper.toEntity(userService.findById(resources.getStudentUser().getId()));
            user.setVerifyStatus(resources.getVerifyStatus());
            if(isVerifyChange)
                user.setVerifyTime(resources.getVerifyTime());
            userService.update(user);
        }

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除学生校友")
    @ApiOperation("删除学生校友")
    @PreAuthorize("@el.check('student:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        studentService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("通过姓名和电话查询学生")
    @ApiOperation("通过姓名和电话查询学生")
    @AnonymousPostMapping(value = "/selstudent")
    public ResponseEntity<Object> selstudent(User user){
        System.out.println(user.toString());
        Student student = studentService.findByNameAndPhone(user.getUsername(), user.getPhone());

        if(student != null){
            user.setVerifyStatus(1);
            user.setDeptId(student.getAcademyDepartment().getId());
            user.setMajorDepartId(student.getMajorDepartId());
        }else{
            user.setVerifyStatus(0);
        }
        //判断是否存在
        user.setCreateBy("微信认证");
        user.setPassword(passwordEncoder.encode("123456"));
        user.setIsAdmin(false);
        user.setEnabled(true);
        user.setEmail(user.getPhone() + "@139.com");
        user.setWxNickName("1");
        UserDto userDto = userService.create(user);
        if(student != null){
            student.setUserId(userDto.getId());
            student.setVerifyStatus(1);
            studentService.update(student);
        }
        return ResponseEntity.ok(user);
    }
}
